package api

import (
	"log"
	"net/http"
	"regexp"

	"github.com/PuerkitoBio/goquery"
	"github.com/kataras/iris/v12"
)

func HspUserInfo(ctx iris.Context) {
	mainurl := "https://www.hspcn.com/Home/main/"

	req, err := http.NewRequest("GET", mainurl, nil)
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	if err != nil {
		log.Println(err.Error())
		ctx.JSON(iris.Map{"flag": false, "msg": err.Error()})
		return
	}

	// 带上 cookie
	cookies := ctx.Request().Cookies()
	for _, ck := range cookies {
		req.AddCookie(ck)
	}
	req.Header.Add("Origin", "https://www.hspcn.com")
	req.Header.Add("Referer", mainurl)
	req.Header.Add("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36 Edg/95.0.1020.30")

	log.Println("正在请求此接口：", req.URL.String())

	httpClient := &http.Client{}
	httpResp, err := httpClient.Do(req)
	if err != nil {
		log.Println(err.Error())
		ctx.JSON(iris.Map{"flag": false, "msg": err.Error()})
		return
	}
	defer httpResp.Body.Close()

	// hspResponse, err := ioutil.ReadAll(httpResp.Body)
	doc, err := goquery.NewDocumentFromReader(httpResp.Body)
	if err != nil {
		log.Println(err.Error())
		return
	}

	maps := []map[string]string{}
	doc.Find("#username").Each(func(i int, cont *goquery.Selection) {
		one := map[string]string{}

		fn := func(str string) string {
			if str == "" {
				return ""
			}
			reg := regexp.MustCompile("[^\u4e00-\u9fa5]+")
			return reg.ReplaceAllString(str, "")
		}
		one["username"] = fn(cont.Text())

		maps = append(maps, one)
	})

	ctx.JSON(iris.Map{"userinfo": maps})
}
